<template>
  <BoTable
    :columns="columns"
    :request="_earthquakeList"
    :row-selection="rowSelection"
    row-key="id"
    ref="tableRef"
  >
    <template #toolbars>
      <Space :size="8">
        <Button :disabled="!selectKeys?.length" @click="onDelete"
          >删除</Button
        ></Space
      >
    </template>
    <template #info="{ record }">
      <div class="eewMessage">
        <div>
          <div>类型：</div>
          <div>
            {{
              record.normalWarning.msgType
                ? sysEventTypeEnum[record.normalWarning.msgType].text
                : '--'
            }}
          </div>
        </div>
        <div>
          <div>震级：</div>
          <div>{{ record.normalWarning.magnitude || '--' }}级</div>
        </div>
        <div>
          <div>烈度：</div>
          <div>{{ record.normalWarning.epiintensity || '--' }}°</div>
        </div>
        <div>
          <div>深度：</div>
          <div>{{ record.normalWarning.focdepth || '--' }}km</div>
        </div>
        <div>
          <div>经度：</div>
          <div>{{ record.normalWarning.epilon || '--' }}°</div>
        </div>
        <div>
          <div>纬度：</div>
          <div>{{ record.normalWarning.epilat || '--' }}°</div>
        </div>
        <div>
          <div>地址：</div>
          <div>{{ record.normalWarning.locname || '--' }}</div>
        </div>
      </div>
    </template>
    <template #warning="{ record }">
      <div class="eewMessage">
        <div>
          <div>预警等级：</div>
          <div>{{ record.warningCountdownVO.warningLevel || '--' }}</div>
        </div>
        <div>
          <div>震中距：</div>
          <div>{{ record.warningCountdownVO.distance || '--' }}km</div>
        </div>
        <div>
          <div>本地烈度：</div>
          <div>{{ record.warningCountdownVO.localIntensity || '--' }}°</div>
        </div>
        <div>
          <div>预警倒计时：</div>
          <div>{{ record.warningCountdownVO.localWarningTime || '--' }}s</div>
        </div>
      </div>
    </template>
    <template #devices="{ record }">
      <div class="info" v-if="Array.isArray(record.projectVO.deviceList)">
        <div v-for="item in record.projectVO?.deviceList">
          {{ item.stationId || '--' }}
        </div>
      </div>
      <div v-else>--</div>
    </template>
  </BoTable>

  <Modal
    v-model:open="flag"
    @ok="handleOk"
    :footer="false"
    wrapClassName="view_modal"
    :destroyOnClose="true"
  >
    <triggerData
      :deviceInfo="deviceInfo"
      :title="showWitch === 'trigger' ? '设备触发数据' : '数据产出'"
      v-model:showWitch="showWitch"
      :fetchInfoApi="() => dataInfo"
      :data="dataInfo"
      :queryParams="queryParams"
      :options="option"
    >
      <template #header v-if="showWitch === 'trigger'"> </template>
    </triggerData>
  </Modal>

  <!-- 预览pdf -->
  <BoPreviewPdf
    title="预览"
    :iframe-url="iframeUrl"
    v-model:open="visible"
  ></BoPreviewPdf>

  <FormModal :columns="item">
    <template #details>
      <div class="generate_error_msg">
        {{ generateErrorMsg || '-' }}
      </div>
    </template>
  </FormModal>

  <globalLoading v-model:visible="showLoading" tip="图表生成中..." />
</template>

<route lang="json">
{
  "name": "地震预警产出",
  "meta": { "title": "地震预警产出" }
}
</route>

<script setup lang="tsx">
import { computed, nextTick, reactive, ref, watch } from 'vue';
import { useFormModal } from '@boeyo/hooks';
import { useDicts, useUserStore } from '@boeyo/portal';
import { download } from '@boeyo/shared';
import { BoFormProps, BoPreviewPdf, BoTable, BoTableProps } from '@boeyo/ui';
import { Button, Modal, Space, message } from 'ant-design-vue';
import dayjs from 'dayjs';
import globalLoading from '@/components/globalLoading/index.vue';
import triggerData from '@/components/triggerData/index.vue';
import { getWaveInfo } from '@/utils/index';
import {
  createNormalWarningDataReport,
  delEarthquake,
  downloadGenerateById,
  earthquakeList,
  fetchHistoryData,
  responseSpectrum,
  signal,
} from './api';

const userStore = useUserStore();
const license = userStore.license;
const showLoading = ref(false);
const { sysEventTypeEnum, sysMagnitudeEnum } = useDicts([
  'sys_event_type',
  'sys_magnitude',
]);
const { FormModal, open } = useFormModal({
  size: 'middle',
  column: 1,
});
const generateErrorMsg = ref('');

const _earthquakeList = async (params: any) => {
  params.startTime = params.earthquakeStartTime?.[0];
  params.endTime = params.earthquakeStartTime?.[1];
  return await earthquakeList(params);
};

const columns = computed<BoTableProps['columns']>(() => [
  {
    title: '发震时间',
    dataIndex: 'earthquakeStartTime',
    valueType: 'dateRange',
    // customRender({ record }) {
    //   return <span>{record.earthquakeStartTime}</span>;
    // },
  },
  {
    title: '震级',
    dataIndex: 'level',
    hideInTable: true,
    valueType: 'select',
    valueEnum: {
      ...sysMagnitudeEnum.value,
    },
  },
  {
    title: '震中地址',
    dataIndex: 'locname',
    hideInTable: true,
  },
  {
    title: '结束时间',
    dataIndex: 'earthquakeEndTime',
    hideInSearch: true,
  },
  {
    title: '地震预警信息',
    dataIndex: 'info',
    hideInSearch: true,
  },
  {
    title: '地震预警响应信息',
    dataIndex: 'warning',
    hideInSearch: true,
  },
  {
    title: '关联设备',
    dataIndex: 'devices',
    hideInSearch: true,
  },
  {
    title: '产出数据',
    dataIndex: 'operation',
    hideInSearch: true,
    fixed: 'right',
    actions: [
      {
        text: '设备触发数据',
        onClick(record) {
          onDevices(record, 'trigger');
        },
      },
      {
        text: '数据产出',
        hidden: !['3', '4', '5'].some((item) =>
          (license.vipPaks as string[]).includes(item),
        ),
        onClick(record) {
          onDevices(record, 'signalNoiseRatio');
        },
      },
    ],
  },
  {
    title: '产出报告',
    dataIndex: 'operation1',
    hideInSearch: true,
    fixed: 'right',
    actions({ record }) {
      const style = {
        color: 'red',
      };
      return [
        {
          text: record.generateId ? (
            '预览'
          ) : (
            <span>
              <span style={style}>！</span>
              <span>预览</span>
            </span>
          ),
          onClick: async (record) => {
            if (!record.generateId) {
              generateErrorMsg.value = record.generateErrorMsg;
              return open({
                title: '日志',
                modalType: 'disabled',
                hideFooter: true,
                request: async (params: any) => {},
                defaultValue: record,
              });
            }

            const result = await downloadGenerateById(record.generateId, 'pdf');
            const blob = new Blob([result.data], { type: 'application/pdf' });
            const imageUrl = URL.createObjectURL(blob);
            iframeUrl.value = imageUrl;
            visible.value = true;
          },
        },
        {
          text: '重新生成',
          hidden: canRegenerate.value,
          onClick: async (record) => {
            canRegenerate.value = true;
            message.loading('报告重新生成中..', 0);
            const res = await createNormalWarningDataReport(record.id);
            message.destroy();
            if (res.code === 200) {
              message.success('报告生成完毕!');
            } else {
              message.info(res.msg);
            }
            canRegenerate.value = false;
            tableRef.value.refresh();
          },
        },
        {
          text: '下载',
          hidden: !record.generateId,
          onClick: async (record) => {
            const res = await downloadGenerateById(record.generateId, 'pdf');
            download(
              res.data as unknown as Blob,
              `data_${dayjs().format('YYYY-MM-DD HH:mm:ss')}.pdf`,
            );
          },
        },
      ];
    },
  },
]);

const item = computed<BoFormProps['columns']>(() => [
  {
    title: '',
    dataIndex: 'details',
    valueType: 'input',
    formItemProps: {
      wrapperCol: { span: 24 },
    },
  },
]);

const iframeUrl = ref();
const visible = ref(false);

const selectKeys = ref<number[]>([]);
const rowSelection = computed<BoTableProps['rowSelection']>(() => {
  return {
    onChange(values) {
      selectKeys.value = values as number[];
    },
  };
});

const handleOk = () => {};
const flag = ref(false);
const dataInfo = ref({});
const queryParams = ref({});
const queryParams2 = computed(() => {
  const start = queryParams.value.startTime;
  const startTime = start
    ? dayjs(start).subtract(15, 'second').format('YYYY-MM-DD HH:mm:ss')
    : '';
  const endTime = start
    ? dayjs(start).subtract(5, 'second').format('YYYY-MM-DD HH:mm:ss')
    : '';
  return { startTime, endTime, stationIds: deviceInfo.value };
});
const onDevices = async (record, type) => {
  // message.loading('图表生成中..', 0);
  showLoading.value = true;
  showWitch.value = type;
  const { projectVO, earthquakeEndTime, earthquakeStartTime } = record;
  deviceInfo.value = projectVO.deviceList.map((i) => i.stationId);
  setTimeout(async () => {
    if (showWitch.value === 'trigger') {
      try {
        const { dataInfo: data, deviceInfoList } = await getWaveInfo(
          deviceInfo.value,
          earthquakeStartTime,
          earthquakeEndTime,
          fetchHistoryData,
        );
        option.value.deviceInfoList = deviceInfoList;
        dataInfo.value = data;
      } catch (error) {
        showLoading.value = false;
      }
    } else {
      queryParams.value = {
        stationIds: deviceInfo.value,
        startTime: earthquakeStartTime,
        endTime: earthquakeEndTime,
      };
      const signalData = await signal(queryParams.value);
      const signalData2 = await signal(queryParams2.value);
      dataInfo.value = {
        result1: signalData.data,
        result2: signalData2.data,
      };
      init(signalData.data);
    }
    showLoading.value = false;
    flag.value = true;
  }, 300);
};

const deviceInfo = ref([]);
const option: any = ref({});
const showWitch = ref();

const tableRef = ref();
const onDelete = async () => {
  const ids = selectKeys.value.join(',');
  Modal.confirm({
    title: '系统提示',
    content: `确认要删除当前选中项数据？`,
    centered: true,
    onOk: async () => {
      await delEarthquake(ids);
      selectKeys.value = [];
      tableRef.value.refresh();
      message.success('操作成功');
    },
  });
};

const canRegenerate = ref(false);

watch(
  () => showWitch.value,
  async (val) => {
    if (val === 'signalNoiseRatio') {
      if (!flag.value) return;
      const signalData = await signal(queryParams.value);
      const signalData2 = await signal(queryParams2.value);
      dataInfo.value = {
        result1: signalData.data,
        result2: signalData2.data,
      };
      init(signalData.data);
    } else if (val === 'waveform') {
      const signalData = await signal(queryParams.value);
      dataInfo.value = signalData.data;
      init(signalData.data);
    } else if (val === 'spectrum') {
      const signalData = await responseSpectrum(queryParams.value);
      dataInfo.value = signalData.data;
      init(signalData.data);
    }
  },
);

const init = (data) => {
  message.destroy();
  if (!Object.keys(data).length) {
    message.info('暂无数据!');
  }

  const resultList = Object.keys(data);
  option.value.deviceInfoList = deviceInfo.value.map((i) => {
    return {
      label: i,
      value: i,
      disabled: !resultList.includes(i.replaceAll('.', '')),
    };
  });
};
</script>

<style scoped lang="scss">
.eewMessage {
  > div {
    margin-bottom: 10px;
    display: flex;
    text-align: left;

    &:last-child {
      margin-bottom: 0;
    }
    div {
      flex: 1;
    }
  }
}

.info {
  display: flex;
  flex-direction: column;
  text-align: center;
  div {
    margin-bottom: 10px;
  }
}
</style>
